package com.yb0os1.decorator.inputstream;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class BufferInputStream extends InputStream {
    private final FileInputStream delegate;
    private final byte[] buffer = new byte[8192];
    private int bufferIndex = -1;
    private int bufferLength = -1;

    public BufferInputStream(FileInputStream delegate) {
        this.delegate = delegate;
    }

    @Override
    public int read() throws IOException {
        if (bufferCanRead()) {
            return readFromBuffer();
        }
        refreshBuffer();
        if (!bufferCanRead()) {
            return -1;
        }
        return readFromBuffer();
    }

    private void refreshBuffer() throws IOException {
        bufferIndex = 0;
        bufferLength = delegate.read(buffer);
    }

    private int readFromBuffer() {
        return buffer[bufferIndex++] & 0xff;
    }

    private boolean bufferCanRead() {
        if (bufferLength == -1) return false;
        if (bufferLength == bufferIndex) return false;
        return true;
    }

    @Override
    public void close() throws IOException {
        super.close();
    }

}
